package org.example.gift.controller;

import javax.validation.Valid;
import java.util.List;

import com.baomidou.mybatisplus.plugins.Page;
import org.example.gift.domain.User;
import org.example.gift.domain.UserAddress;
import org.example.gift.dto.RegisterDto;
import org.example.gift.query.UserQuery;
import org.example.gift.service.IUserService;
import org.example.gift.util.AjaxResult;
import org.example.gift.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public IUserService userService;

    /**
     * 保存和修改公用的
     * @param user  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){

        if( user.getId()!=null)
            userService.updateById(user);
        else
            userService.insert(user);
        return AjaxResult.success();

    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        userService.deleteById(id);
        return AjaxResult.success();

    }
	
    //获取用户
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id")Long id)
    {

        User user = userService.selectById(id);
        return AjaxResult.success(user);

    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping
    public AjaxResult list(){

        List< User> list = userService.selectList(null);
        return AjaxResult.success(list);

    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public AjaxResult json(@RequestBody UserQuery query)
    {
        Page<User> page = new Page<User>(query.getPage(),query.getRows());
        page = userService.selectPage(page);
        PageList pageList = new PageList<User>(page.getTotal(),page.getRecords());
        return AjaxResult.success(pageList);
    }


    @PutMapping("/register")
    public AjaxResult userRegister(@RequestBody @Valid RegisterDto registerDto){

        userService.userRegister(registerDto);
        return AjaxResult.success();

    }




}